<script setup lang="ts">
import { getAllSaleAttrAPI, getAllTradeMarkAPI, getHasSaleAttrAPI, reqAddorupdateSPUAPI, reqSpuImageList, } from '@/apis/spu';
import { trankRes } from '@/types/permission';
import { HasSaleAttr, HasSaleAttrResponseData, SaleAttr, SaleAttrResponseData, SaleAttrValue, SpuHasImg, SpuImg, SPURes, TrankResponseData } from '@/types/spu';
import { UploadFile } from 'element-plus';
import { computed, ref } from 'vue';
//图片上传
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// 子组件触发方法
const emit = defineEmits(['changeScreen'])

//点击取消按钮切换场景
const cancel = () => {
    emit('changeScreen', 0)
}

//上传图片之前校验
const handlerUpload = (file: any) => {
    console.log(file);
    if (file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') {
        if (file.size / 1024 / 1024 < 3) {
            return true
        } else {
            ElMessage.error('上传文件应小于3MB')
            return false
        }
    } else {
        ElMessage.error('上传图片类型必须是png,jpeg.gif')
        return false
    }
}
// 手动删除图片
const handleRemove = (file: UploadFile) => {
    console.log(file)
}

//弹出对话框
const handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url!
    dialogVisible.value = true
}

//存储所有SPU数据
// 存储品牌列表
const tradeMarkList = ref<trankRes[]>([])
//存储图片地址
const imageList = ref<SpuImg[]>([])
//存储已有销售属性
const saleList = ref<SaleAttr[]>([])
//存储全部销售属性
const allsaleList = ref<HasSaleAttr[]>([])
// 定义数据
const spuParams = ref<SPURes>({
    category3Id: '', //收集三级分类的ID
    spuName: '', //SPU的名字
    description: '', //SPU的描述
    tmId: '', //品牌的ID
    spuImageList: [],
    spuSaleAttrList: [],
})
//子组件内部的四个方法
const initHasData = async (spu: SPURes) => {
    spuParams.value = spu
    //获取所有品牌数据
    const res1: TrankResponseData = await getAllTradeMarkAPI()
    // 获取某一个已有SPU全部图片的地址
    const res2: SpuHasImg = await reqSpuImageList(spu.id as number)
    //获取所有已有销售属性
    const res3: SaleAttrResponseData = await getHasSaleAttrAPI(spu.id as number)
    //获取全部商品属性
    const res4: HasSaleAttrResponseData = await getAllSaleAttrAPI()
    //收集所有品牌数据
    tradeMarkList.value = res1.data
    //收集图片地址
    imageList.value = res2.data.map((item) => {
        return {
            name: item.imgName,
            url: item.imgUrl
        }
    })
    //收集已有销售属性
    saleList.value = res3.data
    //收集全部销售属性
    allsaleList.value = res4.data

}
//计算当前spu未拥有的已有属性
const unSelectAttr = computed(() => {
    const unSelectAttr = allsaleList.value.filter((item) => {
        return saleList.value.every(item1 => {
            return item.name !== item1.saleAttrName
        })
    })
    return unSelectAttr
})
//收集未选择已有属性的id和name
const saleAttrNameAndId = ref('')
//添加属性
const addSaleAttr = () => {
    const [baseSaleAttrId, saleAttrName] = saleAttrNameAndId.value.split(':')
    let newSaleAttr: SaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: []
    }
    saleList.value.push(newSaleAttr)
    saleAttrNameAndId.value = ''
}
//属性值的按钮点击事件
const toEdit = (row: SaleAttr) => {
    row.flag = true
    row.saleAttrValue = ''
}
//表单元素失去焦点
const toLook = (row: SaleAttr) => {
    let { baseSaleAttrId, saleAttrValue } = row
    const newSaleValue: SaleAttrValue = {
        baseSaleAttrId,
        saleAttrValueName: saleAttrValue as string
    }
    //非法情况判断
    if ((saleAttrValue as string).trim() == '') {
        ElMessage.error('属性值不能为空')
    }
    const repeat = row.spuSaleAttrValueList.find(item => {
        return item.saleAttrValueName == saleAttrValue as string
    })
    if (repeat) {
        ElMessage.error('属性值不能重复')
        return
    }
    row.spuSaleAttrValueList.push(newSaleValue)
    row.flag = false
}
//保存按钮
const save = async () => {
    //整理参数
    // 照片墙
    spuParams.value.spuImageList = imageList.value.map((item: any) => {
        return {
            imgName: item.name,//图片名字
            imgUrl: (item.response && item.response.data) || item.url
        }
    })
    //销售属性的数据
    spuParams.value.spuSaleAttrList = saleList.value
    await reqAddorupdateSPUAPI(spuParams.value)
    ElMessage.success(spuParams.value.id ? '修改成功' : '添加成功')
    emit('changeScreen', 0)
}

//添加品牌
const initHasAddSPU = async (c3Id: number | string) => {
    //清空数据
    Object.assign(spuParams.value, {
        category3Id: '', //收集三级分类的ID
        spuName: '', //SPU的名字
        description: '', //SPU的描述
        tmId: '', //品牌的ID
        spuImageList: [],
        spuSaleAttrList: [],
    })
    imageList.value=[]
    saleList.value=[]
    saleAttrNameAndId.value=''
    spuParams.value.category3Id = c3Id
    const res1: TrankResponseData = await getAllTradeMarkAPI()
    //获取全部商品属性
    const res4: HasSaleAttrResponseData = await getAllSaleAttrAPI()
    //收集所有品牌数据
    tradeMarkList.value = res1.data
    //收集全部销售属性
    allsaleList.value = res4.data
}
//子组件暴露方法
defineExpose({
    initHasData,
    initHasAddSPU
})

</script>

<template>
    <!-- 表单组件 -->
    <el-form label-width="100px">
        <el-form-item label="SPU名称">
            <el-input placeholder="请输入SPU名称" v-model="spuParams.spuName"></el-input>
        </el-form-item>
        <el-form-item label="SPU品牌">
            <el-select placeholder="请选择" v-model="spuParams.tmId" style="width: 200px;">
                <el-option v-for="item in tradeMarkList" :key="item.id" :label="item.tmName"
                    :value="item.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" placeholder="请输入SPU描述" v-model="spuParams.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU图片">
            <el-upload v-model:file-list="imageList" action="/api/admin/product/fileUpload" list-type="picture-card"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="handlerUpload">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="" style="width: 100%;height: 100%;" />
            </el-dialog>
        </el-form-item>
        <el-form-item label="SPU销售属性">
            <el-select v-model="saleAttrNameAndId" :placeholder="unSelectAttr.length ? `还未选择${unSelectAttr.length}个` : '无'
                " style="width: 200px;margin-right: 10px;">
                <el-option v-for="item in unSelectAttr" :key="item.id" :label="item.name"
                    :value="`${item.id}:${item.name}`"></el-option>
            </el-select>
            <el-button @click="addSaleAttr" type="primary" icon="Plus"
                :disabled="saleAttrNameAndId ? false : true">添加属性</el-button>
            <!-- 表格组件 -->
            <el-table style="margin: 10px 0px;" border :data="saleList">
                <el-table-column type="index" label="序号" width="80px" align="center"></el-table-column>
                <el-table-column prop="saleAttrName" label="销售属性名字" width="150px"></el-table-column>
                <el-table-column prop="prop" label="销售属性值">
                    <template style="margin: 0 5px;" #="{ row }">
                        <el-tag style="margin: 0px 5px" @close="row.spuSaleAttrValueList.splice(index, 1)"
                            v-for="(item, index) in row.spuSaleAttrValueList" :key="row.id" class="mx-1" closable>
                            {{ item.saleAttrValueName }}
                        </el-tag>
                        <!-- 编辑模式 -->
                        <el-input @blur="toLook(row)" v-model="row.saleAttrValue" v-if="row.flag == true"
                            style="width: 100px;" size="small" placeholder="请输入属性值"></el-input>
                        <el-button @click="toEdit(row)" v-else type="primary" icon="Plus" size="small"></el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="prop" label="操作" width="150px">
                    <template #="{ $index }">
                        <el-button type="primary" icon="Delete" size="small"
                            @click="saleList.splice($index, 1)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <!-- 底部按钮组件 -->
            <el-button type="primary" @click="save" :disabled="saleList?.length > 0 ? false : true">保存</el-button>
            <el-button type="primary" @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<style scoped lang="scss"></style>
